function Greduced = reduceG(G,ngen)
% REDUCEG Reduces the number of generators of a given zonotope
% ---------------------------------------------------------------------------
% DESCRIPTION
% ---------------------------------------------------------------------------
% Reduce the number of generators of a given zonotope
%
% ---------------------------------------------------------------------------
% INPUT
% ---------------------------------------------------------------------------
% G    - Original generators of a given zonotope
% ngen - number of new generators
%
% ---------------------------------------------------------------------------
% OUTPUT
% ---------------------------------------------------------------------------
% Greduced  - New generators

    if ngen>size(G,2) || ngen<size(G,1)
        Greduced = G;
%         error('REDUCE: Number of new generators not valid');
    else
    
    n = size(G,1);    
    
    Greduced = G(:,sum(G,1)~=0);
    
    dime = size(Greduced,2);
    if (dime - floor(dime / n)*n)~=0
        Greduced = [Greduced zeros(size(Greduced,1),1)];
    end
    
    normG = sqrt(sum(Greduced.^2,1));
    [~, ind] = sort(normG,'descend');
    
    Greduced = Greduced(:,ind);
    
    if size(Greduced,2) > ngen
        tmp1 = Greduced(:,1:ngen-n);
        tmp2 = Greduced(:,ngen-n+1:end);
        tmp3 = zeros(n,n);
        for i=1:n
            tmp3(i,i)=sum(abs(tmp2(i,:)));
        end
        Greduced = [tmp1 tmp3];
    end
    end
end